package com.qfedu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.qfedu.entity.AdinmEntity;
import com.qfedu.entity.RolesEntity;
import com.qfedu.kit.StringUtil;
import com.qfedu.service.AdminService;
import com.qfedu.util.Page;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Controller
public class AdminController {

    @Reference(check = false)
    AdminService adminService;

    //跳转没有权限页面
    @RequestMapping("jumpnotrolr")
    public String jumpnote() {
        return "notRole";
    }

    //跳转登录页
    @RequestMapping("jump")
    public String jumplogin() {
        return "Login";
    }

    //登录
    @RequestMapping("logout")
    public String logout() {

        Subject subject = SecurityUtils.getSubject();

        subject.logout();

        return "Login";
    }

    //跳转注册页面
    @RequestMapping("jumpregister")
    public String jumpregister() {
        return "register";
    }

    //跳转首页
    @RequestMapping("index")
    public String indexas() {
        return "index";
    }


    //登录跳转首页
    @RequestMapping("jumpindex")
    public String jumpindex(String username,String password,HttpServletRequest request) {



        Subject currentUser = SecurityUtils.getSubject();

        //构建一个token
        UsernamePasswordToken token = new UsernamePasswordToken(username,DigestUtils.md5DigestAsHex((username+password).getBytes()));

       // token.setRememberMe(true);  //记住我

        try {

            currentUser.login(token);

        } catch (UnknownAccountException uae) {

            request.setAttribute("msg", "用户名与密码错误");
            return "Login";

        } catch (IncorrectCredentialsException ice) {

            request.setAttribute("msg", "用户名与密码错误");
            return "Login";

        } catch (LockedAccountException lae) {

            request.setAttribute("msg", "用户名已被锁定");
            return "Login";

        } catch (AuthenticationException ae) {
            request.setAttribute("msg", "用户名与密码错误");
            return "Login";
        }

        AdinmEntity user = adminService.queryuserbyname(username);
        System.out.println(user);
        request.getSession().setAttribute("user",user);
        return "index";

    }



    //注册
    @RequestMapping("register")
    public String regirster(String username, String password, HttpServletRequest request) {

        System.out.println(username + password);
        if (StringUtil.isEnpty(username)) {
            request.getSession().setAttribute("msg", "用户名不能为空");
            return "register";
        }
        if (StringUtil.isEnpty(username)) {
            request.getSession().setAttribute("msg", "密码不能为空");
            return "register";
        }
        //注册的时候，把密码下面用下面的方法进行盐值加密
        String hashAlgorithmName = "MD5";  //加密算法
        String credentials = password;   //密码本身
        Object salt = username;
        int hashIterations = 1;  //加密次数
        SimpleHash sh = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);

        String pass = sh.toString();


        boolean user = adminService.insertuser(username, pass);
        if (user) {
            return "Login";
        } else {
            return "register";
        }


    }

    //跳转管理员管理首页,查询所有管理员并做分页
    @RequestMapping("mapperindex")
    public String jumpadmininde(AdinmEntity ad,HttpServletRequest request) {

        Page PageInfo = adminService.mapperList(ad);
        RolesEntity ro = new RolesEntity();
        ro.setPageNum(ad.getPageNum());
        ro.setPageSize(ad.getPageSize());
        Page page = adminService.mapperListrole(ro);


        request.setAttribute("PageInfo",PageInfo);
        request.setAttribute("page",page);
        return "adminindex";
    }

    @RequestMapping("jumproleindex")
    public String jumorole(AdinmEntity ad,HttpServletRequest request) {
        RolesEntity ro = new RolesEntity();
        ro.setPageNum(ad.getPageNum());
        ro.setPageSize(ad.getPageSize());
        Page page = adminService.mapperListrole(ro);



        request.setAttribute("page",page);
        return "roleindex";
    }

    //编辑个人页面
    @RequestMapping("jumpedit")
    public String jumpedit(){
        return "adminedit";
    }

    //提交编辑个人页面
    @RequestMapping("adminfinedit")
    @ResponseBody
    public String adminedty(AdinmEntity ad, MultipartFile headimage,HttpServletRequest request){


       /*//指定文件上传存放的路径
        String fileDir = "C:\\Users\\86181\\Desktop\\sdsds\\";
        File dir = new File(fileDir);

        //判断目录存不存在，不存在创建目录
        if (!dir.exists()){
            dir.mkdirs();
        }

        //获取文件名
        String originalFileName = headimage.getOriginalFilename();

        //生成文件
        File file = new File(dir, originalFileName);

        //构建文件名称
        String filname =headimage.getOriginalFilename();*/




     /*   //传输内容
        try {
            headimage.transferTo(file);
            System.out.println("上传文件成功！");
        } catch (IOException e) {
            System.out.println("上传文件失败！");
            e.printStackTrace();
        }

        //文件路径
        String newFileName = fileDir +originalFileName ;

        //打开通道
        FtpJSch ftpJSch = FtpJSch.getConnect();

        //文件上传
        String name = FtpJSch.upload(newFileName);

        //2、删除本地文件
        //file.delete();
            ad.setAimage("http://47.99.61.196/images/"+name);*/


        //获取头像名
        String filename = StringUtil.getUUID().substring(0,9)+headimage.getOriginalFilename();
        ad.setAimage("userimages"+ File.separator+filename);

        //注册的时候，把密码下面用下面的方法进行盐值加密
        String hashAlgorithmName = "MD5";  //加密算法
        String credentials = ad.getApass();   //密码本身
        Object salt = ad.getAname();
        int hashIterations = 1;  //加密次数
        SimpleHash sh = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);

        String pass = sh.toString();
        ad.setApass(pass);
        boolean adminedit = adminService.adminedit(ad);

        if(adminedit) {
            String filePath = "static" + File.separator + "userimages";
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                String path = filePath + File.separator + filename;
                InputStream is = headimage.getInputStream();
                FileOutputStream fos = new FileOutputStream(path);
                System.out.println(path);
                FileCopyUtils.copy(is, fos);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return "0000";
            }else {
                return "0001";
            }



    }
        //跳进管理员修改页面做回填
    @RequestMapping("queryrole")
    @ResponseBody
    public String queryrole(Integer aid,HttpServletRequest request){
        if (aid != null){
            //查询所有角色
            AdinmEntity ad = new AdinmEntity();
            ad.setAid(aid);
            AdinmEntity pojolist = adminService.adminList(ad);


            request.getSession().setAttribute("pojolist",pojolist);

            return "0000";
        }else {
            return "0001";
        }

    }
        //跳进角色修改页面做回填
    @RequestMapping("selrolr")
    @ResponseBody
    public String selrole(RolesEntity ro,HttpServletRequest request){
        if (ro !=null){
            //查询所有角色

            RolesEntity roles = adminService.selrole(ro);


            request.getSession().setAttribute("roles",roles);

            return "0000";
        }else {
            return "0001";
        }

    }

    @RequestMapping("finaledit")
    public String jumpadmiedit(HttpServletRequest request){
        List<RolesEntity> roles = adminService.queryroles();
        AdinmEntity pojolist = (AdinmEntity) request.getSession().getAttribute("pojolist");
        for (RolesEntity role :roles){
            for (RolesEntity use : pojolist.getRolesEntity()){
                if (role.getRid() == use.getRid()){
                   role.setStatus(2);
                }
            }
        }
        request.setAttribute("roles",roles);

        return "adminedbyid";
    }

    @RequestMapping("tanchuedit")
    public String jumproleedit(HttpServletRequest request){


        return "rolesedit";
    }

    @RequestMapping("tijiaoroleedit")
    @ResponseBody
    public String tadad(RolesEntity ro,HttpServletRequest request){

        boolean editrole = adminService.editrole(ro);
        if (editrole){
            return "0000";
        }else {
            return "0001";
        }
    }


    @RequestMapping("tijiao")
    @ResponseBody
    public String zuihzong(AdinmEntity ad,  MultipartFile headfile, HttpServletRequest request){

        System.out.println(ad);
        System.out.println(headfile);
        boolean sendadmin = adminService.sendadmin(ad);

        if (sendadmin){
            return "0000";
        }else {
            return "0001";
        }


    }


    //删除管理员
    @RequestMapping("deletebysts")
    @ResponseBody
    public String deletebyaid(Integer aid){
        boolean hh = adminService.deletebyid(aid);
        if (hh){
            return "0000";
        }else {
            return "0001";
        }
    }

    //启用管理员
    @RequestMapping("qiyongbyid")
    @ResponseBody
    public String qiyongbyid(Integer aid){
        boolean hh = adminService.qiyongbyid(aid);
        if (hh){
            return "0000";
        }else {
            return "0001";
        }
    }

    //删除所有
    @RequestMapping("delAlladmin")
    @ResponseBody
    public String delalladmin(String ids,HttpServletRequest request){

        System.out.println(ids);
        boolean deAll = adminService.deAll(ids);
        if (deAll){
            return "0000";
        }else {
            return "0001";
        }
    }

    //跳转admin添加页面
    @RequestMapping("admintijiao")
    public String jumadd(){
        return "addminadd";
    }


    //admin页面提交
    @RequestMapping("adminsend")
    @ResponseBody
    public String addadmina(AdinmEntity ad, MultipartFile headimage,HttpServletRequest request){

        //获取头像名
        String filename = StringUtil.getUUID().substring(0,9)+headimage.getOriginalFilename();
        ad.setAimage("userimages"+ File.separator+filename);
        //注册的时候，把密码下面用下面的方法进行盐值加密
        String hashAlgorithmName = "MD5";  //加密算法
        String credentials = ad.getApass();   //密码本身
        Object salt = ad.getAname();
        int hashIterations = 1;  //加密次数
        SimpleHash sh = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);

        String pass = sh.toString();
        ad.setApass(pass);
        boolean adminedit = adminService.tiaoadmin(ad);
        if(adminedit) {
            String filePath = "static" + File.separator + "userimages";
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                String path = filePath + File.separator + filename;
                InputStream is = headimage.getInputStream();
                FileOutputStream fos = new FileOutputStream(path);
                System.out.println(path);
                FileCopyUtils.copy(is, fos);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return "0000";
        }else {
            return "0001";
        }

    }

    @RequestMapping("roleadd")
    public String jumproledeit(){
        return "addrole";
    }

    @RequestMapping("tijiaoroleadd")
    @ResponseBody
    public String addroletijiao(RolesEntity ro){
        boolean addroleti = adminService.addroleti(ro);
        if (addroleti){
            return "0000";
        }else {
            return "0001";
        }
    }

    @RequestMapping("deleterole")
    @ResponseBody
    public String deleterole(int rid){

        boolean deleterole = adminService.deleterole(rid);
        if (deleterole){
            return "0000";
        }else {
            return "0001";
        }
    }
}
